package top.archiesean.authorize.support.core;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenClaimsSet;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
import top.archiesean.common.core.constant.SecurityConstants;
import top.archiesean.common.security.domain.SeanUser;

/**
 * @author ArchieSean
 * @description 自定义accessToken
 * @date 2024-01-06 21:49
 */
public class CustomOAuth2TokenCustomizer implements OAuth2TokenCustomizer<OAuth2TokenClaimsContext> {
    @Override
    public void customize(OAuth2TokenClaimsContext context) {
        OAuth2TokenClaimsSet.Builder claims = context.getClaims();
        //获取客户端id
        String clientId = context.getRegisteredClient().getClientId();
        //客户端id放入token
        claims.claim(SecurityConstants.CLIENT_ID, clientId);
        //客户端模式不需要返回用户信息
        if (SecurityConstants.CLIENT_CREDENTIALS.equalsIgnoreCase(context.getAuthorizationGrantType().getValue())) {
            return;
        }
        SeanUser user = (SeanUser) context.getPrincipal().getPrincipal();
        claims.claim(SecurityConstants.USERNAME, user.getUsername());
        claims.claim(SecurityConstants.DETAILS_USER_ID, user.getId());
        claims.claim(SecurityConstants.DETAILS_USER, user);
    }
}
